#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Database verification script
"""

import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.absolute()
sys.path.insert(0, str(project_root))

def check_database():
    """Check database connection and tables"""
    try:
        from backend.config.database import engine, get_db_session
        from sqlalchemy import inspect, text
        
        print("🔍 正在检查数据库连接...")
        
        # Test basic connection
        with engine.connect() as conn:
            result = conn.execute(text("SELECT 1"))
            print("✅ 数据库连接成功!")
        
        # Get table information
        inspector = inspect(engine)
        tables = inspector.get_table_names()
        
        print(f"📋 数据库中的表 ({len(tables)}个):")
        for table in tables:
            print(f"  - {table}")
            
        # Check specific tables we need
        required_tables = ['load_data', 'weather_daily']
        missing_tables = [t for t in required_tables if t not in tables]
        
        if missing_tables:
            print(f"❌ 缺少必要的表: {missing_tables}")
        else:
            print("✅ 所有必要的表都存在!")
            
        # Check load_data table structure if it exists
        if 'load_data' in tables:
            print("\n🔍 检查 load_data 表结构:")
            columns = inspector.get_columns('load_data')
            for col in columns:
                print(f"  - {col['name']}: {col['type']}")
                
        # Check weather_daily table structure if it exists  
        if 'weather_daily' in tables:
            print("\n🔍 检查 weather_daily 表结构:")
            columns = inspector.get_columns('weather_daily')
            for col in columns:
                print(f"  - {col['name']}: {col['type']}")
        
        # Test a simple query
        print("\n🔍 测试简单查询...")
        db = get_db_session()
        try:
            if 'load_data' in tables:
                result = db.execute(text("SELECT COUNT(*) as count FROM load_data")).first()
                print(f"✅ load_data 表有 {result.count} 条记录")
            else:
                print("⚠️  load_data 表不存在")
                
            if 'weather_daily' in tables:
                result = db.execute(text("SELECT COUNT(*) as count FROM weather_daily")).first()
                print(f"✅ weather_daily 表有 {result.count} 条记录")
            else:
                print("⚠️  weather_daily 表不存在")
                
        except Exception as e:
            print(f"❌ 查询测试失败: {e}")
        finally:
            db.close()
            
    except Exception as e:
        print(f"❌ 数据库检查失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    check_database()